package vip.zhenzicheng.concurrent_program.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步编排简单使用demo
 *
 * @author zhenzicheng
 * @date 2022-06-04 10:55
 */
public class CompletableFutureDemo1 {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    // 无返回值的方式
    noReturnFunc();

    // 有返回值的方式
    returnFunc();
  }

  public static void noReturnFunc() throws ExecutionException, InterruptedException {
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
      System.out.println(Thread.currentThread().getName() + "\t --------come in");
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });
    System.out.println(future.get());
  }

  public static void returnFunc() throws ExecutionException, InterruptedException {
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
      System.out.println(Thread.currentThread().getName());
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return "hello supplyAsync";
    });
    System.out.println(completableFuture.get());
  }
}
